from datetime import date, datetime
from google.appengine.api.urlfetch import fetch
from horseanalysis.lib.hkjc_fetcher.fetcher_base import FetcherBase
from horseanalysis.model.quinella import Quinella
from horseanalysis.model.race import Race
import re

class QuinellaFetcher(FetcherBase):
  def getUrl(self):
    return "http://bet.hkjc.com/racing/getXML.aspx?type=jcbwracing_full&date=%(date_query)s&venue=%(venue)s&raceno=%(race_no)d&pool=qin&tag=QIN/RACE" % \
      {'date_query': self.date_query, 'venue': self.venue, 'race_no': self.race_no}
    
  def getData(self):
    data = fetch(self.getUrl())
    self.batch_time.update_quinella(data.content)
    return data.content
    
  def getResult(self):
    data = self.getData()
    items = []
    for result in re.finditer(r"([0-9]*)-([0-9.]*)=([0-9.A-Z]*)", data):
      odds = result.group(3)
      if odds == 'SCR':
        odds = '-1.0'
      items.append({'first_horse_no':int(result.group(1)), 'second_horse_no':int(result.group(2)), 'odds':float(odds)})
    
    for item in items:
      Quinella.create_new_entry(Quinella, self.race, self.batch_time, item['first_horse_no'], item['second_horse_no'], item['odds'])